<template>
  <div class="salary-comparison">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>工资对比分析</h2>
    </div>

    <!-- 对比条件 -->
    <div class="comparison-form">
      <el-card header="对比条件设置" class="form-card">
        <el-form :model="comparisonForm" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="对比类型">
                <el-radio-group v-model="comparisonForm.type">
                  <el-radio label="employee">员工对比</el-radio>
                  <el-radio label="period">时期对比</el-radio>
                  <el-radio label="department">部门对比</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="对比月份">
                <el-date-picker
                  v-model="comparisonForm.months"
                  type="monthrange"
                  range-separator="至"
                  start-placeholder="开始月份"
                  end-placeholder="结束月份"
                  format="YYYY-MM"
                  value-format="YYYY-MM"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 员工对比 -->
          <div v-if="comparisonForm.type === 'employee'">
            <el-form-item label="选择员工">
              <el-select
                v-model="comparisonForm.employees"
                multiple
                placeholder="请选择要对比的员工（最多5个）"
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="employee in employeeList"
                  :key="employee.id"
                  :label="employee.name"
                  :value="employee.id"
                  :disabled="comparisonForm.employees.length >= 5 && !comparisonForm.employees.includes(employee.id)"
                />
              </el-select>
            </el-form-item>
          </div>

          <!-- 时期对比 -->
          <div v-if="comparisonForm.type === 'period'">
            <el-form-item label="选择员工">
              <el-select
                v-model="comparisonForm.selectedEmployee"
                placeholder="请选择员工"
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="employee in employeeList"
                  :key="employee.id"
                  :label="employee.name"
                  :value="employee.id"
                />
              </el-select>
            </el-form-item>
          </div>

          <!-- 部门对比 -->
          <div v-if="comparisonForm.type === 'department'">
            <el-form-item label="员工类型">
              <el-checkbox-group v-model="comparisonForm.employeeTypes">
                <el-checkbox label="FULL_TIME">全职员工</el-checkbox>
                <el-checkbox label="PART_TIME">兼职员工</el-checkbox>
                <el-checkbox label="TEMPORARY">临时工</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </div>

          <el-form-item>
            <el-button type="primary" @click="handleCompare" :loading="comparing">
              开始对比
            </el-button>
            <el-button @click="handleResetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 对比结果 -->
    <div v-if="comparisonData" class="comparison-result">
      <!-- 统计卡片 -->
      <div class="stats-cards">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-value">{{ comparisonData.totalEmployees }}</div>
                <div class="stat-label">对比员工数</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-value">¥{{ comparisonData.avgSalary }}</div>
                <div class="stat-label">平均工资</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-value">¥{{ comparisonData.maxSalary }}</div>
                <div class="stat-label">最高工资</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-value">¥{{ comparisonData.minSalary }}</div>
                <div class="stat-label">最低工资</div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 图表展示 -->
      <div class="charts-section">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card header="工资对比柱状图" class="chart-card">
              <div ref="barChartRef" class="chart-container"></div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card header="工资趋势图" class="chart-card">
              <div ref="lineChartRef" class="chart-container"></div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 详细数据表格 -->
      <div class="data-table">
        <el-card header="详细对比数据" class="table-card">
          <div class="table-toolbar">
            <el-button type="success" @click="handleExportData">
              <el-icon><Download /></el-icon>
              导出数据
            </el-button>
          </div>

          <el-table
            :data="comparisonData.details"
            stripe
            border
            :default-sort="{ prop: 'totalSalary', order: 'descending' }"
          >
            <el-table-column prop="employeeName" label="员工姓名" width="120" />
            <el-table-column prop="employeeType" label="员工类型" width="100">
              <template #default="{ row }">
                <el-tag :type="getEmployeeTypeTagType(row.employeeType)">
                  {{ getEmployeeTypeText(row.employeeType) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="month" label="月份" width="100" />
            <el-table-column prop="baseSalary" label="基本工资" width="100" sortable>
              <template #default="{ row }">
                ¥{{ row.baseSalary }}
              </template>
            </el-table-column>
            <el-table-column prop="workDays" label="工作天数" width="100" sortable />
            <el-table-column prop="workHours" label="工作小时" width="100" sortable />
            <el-table-column prop="overtimePay" label="加班费" width="100" sortable>
              <template #default="{ row }">
                ¥{{ row.overtimePay }}
              </template>
            </el-table-column>
            <el-table-column prop="performanceBonus" label="绩效奖金" width="120" sortable>
              <template #default="{ row }">
                ¥{{ row.performanceBonus }}
              </template>
            </el-table-column>
            <el-table-column prop="totalSalary" label="总工资" width="120" sortable>
              <template #default="{ row }">
                <span class="total-salary">¥{{ row.totalSalary }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="growthRate" label="增长率" width="100">
              <template #default="{ row }">
                <span :class="getGrowthRateClass(row.growthRate)">
                  {{ row.growthRate }}%
                </span>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>

      <!-- 分析报告 -->
      <div class="analysis-report">
        <el-card header="分析报告" class="report-card">
          <div class="report-content">
            <h4>工资分析总结</h4>
            <ul>
              <li v-for="insight in comparisonData.insights" :key="insight">
                {{ insight }}
              </li>
            </ul>
            
            <h4>建议</h4>
            <ul>
              <li v-for="recommendation in comparisonData.recommendations" :key="recommendation">
                {{ recommendation }}
              </li>
            </ul>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Download } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { getSalaryComparison } from '@/api/salary'
import { getActiveEmployees } from '@/api/employee'

// 响应式数据
const comparing = ref(false)
const employeeList = ref([])
const comparisonData = ref(null)
const barChartRef = ref(null)
const lineChartRef = ref(null)
let barChart = null
let lineChart = null

// 对比表单
const comparisonForm = reactive({
  type: 'employee',
  months: [],
  employees: [],
  selectedEmployee: null,
  employeeTypes: []
})

// 获取员工列表
const fetchEmployeeList = async () => {
  try {
    const response = await getActiveEmployees()
    employeeList.value = response.data || []
  } catch (error) {
    ElMessage.error('获取员工列表失败')
  }
}

// 开始对比
const handleCompare = async () => {
  if (!validateForm()) {
    return
  }

  comparing.value = true
  try {
    const params = {
      type: comparisonForm.type,
      startMonth: comparisonForm.months[0],
      endMonth: comparisonForm.months[1]
    }

    if (comparisonForm.type === 'employee') {
      params.employeeIds = comparisonForm.employees
    } else if (comparisonForm.type === 'period') {
      params.employeeId = comparisonForm.selectedEmployee
    } else if (comparisonForm.type === 'department') {
      params.employeeTypes = comparisonForm.employeeTypes
    }

    const response = await getSalaryComparison(params)
    comparisonData.value = response.data
    
    // 渲染图表
    await nextTick()
    renderCharts()
    
    ElMessage.success('对比分析完成')
  } catch (error) {
    ElMessage.error('对比分析失败')
  } finally {
    comparing.value = false
  }
}

// 表单验证
const validateForm = () => {
  if (!comparisonForm.months || comparisonForm.months.length !== 2) {
    ElMessage.warning('请选择对比月份范围')
    return false
  }

  if (comparisonForm.type === 'employee' && comparisonForm.employees.length === 0) {
    ElMessage.warning('请选择要对比的员工')
    return false
  }

  if (comparisonForm.type === 'period' && !comparisonForm.selectedEmployee) {
    ElMessage.warning('请选择员工')
    return false
  }

  if (comparisonForm.type === 'department' && comparisonForm.employeeTypes.length === 0) {
    ElMessage.warning('请选择员工类型')
    return false
  }

  return true
}

// 重置表单
const handleResetForm = () => {
  Object.assign(comparisonForm, {
    type: 'employee',
    months: [],
    employees: [],
    selectedEmployee: null,
    employeeTypes: []
  })
  comparisonData.value = null
  
  // 销毁图表
  if (barChart) {
    barChart.dispose()
    barChart = null
  }
  if (lineChart) {
    lineChart.dispose()
    lineChart = null
  }
}

// 渲染图表
const renderCharts = () => {
  if (!comparisonData.value) return

  // 渲染柱状图
  renderBarChart()
  
  // 渲染折线图
  renderLineChart()
}

// 渲染柱状图
const renderBarChart = () => {
  if (barChart) {
    barChart.dispose()
  }

  barChart = echarts.init(barChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['基本工资', '加班费', '绩效奖金', '总工资']
    },
    xAxis: {
      type: 'category',
      data: comparisonData.value.details.map(item => item.employeeName)
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '¥{value}'
      }
    },
    series: [
      {
        name: '基本工资',
        type: 'bar',
        data: comparisonData.value.details.map(item => item.baseSalary),
        itemStyle: { color: '#5470c6' }
      },
      {
        name: '加班费',
        type: 'bar',
        data: comparisonData.value.details.map(item => item.overtimePay),
        itemStyle: { color: '#91cc75' }
      },
      {
        name: '绩效奖金',
        type: 'bar',
        data: comparisonData.value.details.map(item => item.performanceBonus),
        itemStyle: { color: '#fac858' }
      },
      {
        name: '总工资',
        type: 'bar',
        data: comparisonData.value.details.map(item => item.totalSalary),
        itemStyle: { color: '#ee6666' }
      }
    ]
  }

  barChart.setOption(option)
}

// 渲染折线图
const renderLineChart = () => {
  if (lineChart) {
    lineChart.dispose()
  }

  lineChart = echarts.init(lineChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['工资趋势']
    },
    xAxis: {
      type: 'category',
      data: comparisonData.value.details.map(item => item.month)
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '¥{value}'
      }
    },
    series: [
      {
        name: '工资趋势',
        type: 'line',
        data: comparisonData.value.details.map(item => item.totalSalary),
        smooth: true,
        itemStyle: { color: '#5470c6' },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(84, 112, 198, 0.3)' },
              { offset: 1, color: 'rgba(84, 112, 198, 0.1)' }
            ]
          }
        }
      }
    ]
  }

  lineChart.setOption(option)
}

// 导出数据
const handleExportData = () => {
  ElMessage.info('导出功能待实现')
}

// 获取员工类型标签类型
const getEmployeeTypeTagType = (type) => {
  const typeMap = {
    FULL_TIME: 'success',
    PART_TIME: 'warning',
    TEMPORARY: 'info'
  }
  return typeMap[type] || 'info'
}

// 获取员工类型文本
const getEmployeeTypeText = (type) => {
  const typeMap = {
    FULL_TIME: '全职',
    PART_TIME: '兼职',
    TEMPORARY: '临时工'
  }
  return typeMap[type] || type
}

// 获取增长率样式类
const getGrowthRateClass = (rate) => {
  if (rate > 0) return 'growth-positive'
  if (rate < 0) return 'growth-negative'
  return 'growth-neutral'
}

// 组件挂载时获取数据
onMounted(() => {
  fetchEmployeeList()
})
</script>

<style scoped>
.salary-comparison {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.comparison-form {
  margin-bottom: 20px;
}

.form-card,
.chart-card,
.table-card,
.report-card {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.form-card :deep(.el-card__header),
.chart-card :deep(.el-card__header),
.table-card :deep(.el-card__header),
.report-card :deep(.el-card__header) {
  background-color: #f5f7fa;
  font-weight: 600;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.stat-item {
  padding: 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.charts-section {
  margin-bottom: 20px;
}

.chart-container {
  height: 300px;
  width: 100%;
}

.data-table {
  margin-bottom: 20px;
}

.table-toolbar {
  margin-bottom: 15px;
  text-align: right;
}

.total-salary {
  font-weight: 600;
  color: #52c41a;
}

.growth-positive {
  color: #52c41a;
  font-weight: 600;
}

.growth-negative {
  color: #ff4d4f;
  font-weight: 600;
}

.growth-neutral {
  color: #666;
}

.analysis-report {
  margin-bottom: 20px;
}

.report-content h4 {
  color: #303133;
  margin: 15px 0 10px 0;
}

.report-content ul {
  margin: 0 0 15px 0;
  padding-left: 20px;
}

.report-content li {
  margin-bottom: 5px;
  color: #606266;
  line-height: 1.6;
}

.el-table {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
</style>